package com.test.iotest.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Iterator;

public class NoBlockAllowRecClient {
    public static void main(String[] args) throws IOException {
        //建立一个通道并绑定到指定host
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9000));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        //打开一个文件通道,从指定位置读取文件。
        FileChannel fileChannel = FileChannel.open(Paths.get("./test.png"), StandardOpenOption.READ);
        //生成一个buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将文件通道里的数据写入到buffer里
        while (fileChannel.read(buffer) != -1) {
            //改变buffer为读模式
            buffer.flip();
            //从buffer中读出数据，到网络通道
            socketChannel.write(buffer);
            buffer.clear();
        }
        int select = selector.select();
        while (select > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    SocketChannel socketChannel1 = (SocketChannel) key.channel();
                    int read = socketChannel1.read(buffer);
                    if (read > 0) {
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, read));
                    }
                }
                iterator.remove();
            }
        }
        fileChannel.close();
        socketChannel.close();
    }
}
